package net.cyl.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.cyl.config.OSSConfig;
import net.cyl.service.FileService;
import net.cyl.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    private OSSConfig ossConfig;
    @Override
    public String uploadFile(MultipartFile file) {
        String bucketName = ossConfig.getBucketName();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        // TODO: upload file to OSS

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String originFilename = file.getOriginalFilename();

        LocalDateTime ldt  = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String folder = formatter.format(ldt);
        String fileName = CommonUtil.generateUUID();
        String fileExtension = originFilename.substring(originFilename.lastIndexOf("."));

        String newFilename = "user/"+folder+"/"+fileName+fileExtension;
        try {
             PutObjectResult putObjectResult = ossClient.putObject(bucketName, newFilename, file.getInputStream());
            return "https://"+bucketName+"."+endpoint+"/"+newFilename;
        } catch (IOException e) {
            log.error("文件上传失败"+e.getMessage());
        }
        finally {
            ossClient.shutdown();
        }
        return "";
    }
}
